import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<Integer> future = executor.submit(() -> {
            Thread.sleep(1000);
            return 42;
        });

// 主线程继续执行其他操作...

        try {
            Integer result = future.get(2, TimeUnit.SECONDS); // 超时2秒
            System.out.println("结果: " + result);
        } catch (TimeoutException e) {
            future.cancel(true); // 超时后取消任务
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            executor.shutdown();
        }
    }
}
